package com.xms.schema.api.controller;

import com.xms.core.exception.XmsException;
import com.xms.core.model.KeyValuePair;
import com.xms.schema.api.model.CreateOptionSetModel;
import com.xms.schema.entity.OptionSet;
import com.xms.schema.entity.OptionSetDetail;
import com.xms.schema.service.optionset.IOptionSetCreaterService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * OptionSetCreaterController
 * </p>
 *
 * @author migo
 * @since 2021/9/19
 */
@RestController
@RequestMapping("/{org}/api/schema/optionset")
public class OptionSetCreaterController extends ApiBaseController {
    private IOptionSetCreaterService _optionSetCreaterService;
    @Autowired
    public void OptionSetCreaterController(IOptionSetCreaterService optionSetCreaterService) {
        _optionSetCreaterService = optionSetCreaterService;
    }

    @ApiOperation("新建选项集")
    @PostMapping("create")
    public JsonResultObject create(@RequestBody CreateOptionSetModel model) throws XmsException, SQLException {
        if(CollectionUtil.isEmpty(model.optionSetName)
        || CollectionUtil.isEmpty(model.optionSetValue)){
            return JNotSpecifiedParams("选项的名称与值");
        }
        OptionSet os = new OptionSet();
        os.setOptionsetid(UUIDUtil.get());
        os.setName(model.name);
        os.setIspublic(true);
        os.setOrganizationid(_currentUser.getUser().OrganizationId);
        os.setDescription(model.description);
        os.setCreatedon(LocalDateTime.now());
        os.setCreatedby(_currentUser.getUser().SystemUserId);
        List<OptionSetDetail> details = new ArrayList<>();
        int i = 0;
        for (String item : model.optionSetName)
        {
            if (StringUtil.isEmpty(item)) continue;
            OptionSetDetail osd = new OptionSetDetail();
            osd.setOptionsetid(os.getOptionsetid());
            osd.setOptionsetdetailid(UUIDUtil.get());
            osd.setName(item);
            osd.setValue(model.optionSetValue[i]);
            osd.setIsselected(model.isSelectedOption[i]);
            osd.setDisplayorder(i);
            details.add(osd);
            i++;
        }
        os.setItems(details);
        return _optionSetCreaterService.create(os) ? JCreateSuccess(KeyValuePair.build("id", os.getOptionsetid())) : JCreateFailure();
    }
}
